from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import Optional, Dict, Any

from database import get_db
from services import merchant_service
import schemas

router = APIRouter()

# 统一响应格式
def create_response(code: int = 200, message: str = "成功", data: Any = None):
    return {
        "code": code,
        "message": message,
        "data": data
    }

@router.get("/list", response_model=schemas.Response)
async def list_merchants(
    name: Optional[str] = None,
    code: Optional[str] = None,
    status: Optional[int] = None,
    page_num: int = 1,
    page_size: int = 10,
    db: Session = Depends(get_db)
):
    """
    获取商户列表
    
    - **name**: 商户名称，支持模糊查询
    - **code**: 商户编码，支持模糊查询
    - **status**: 商户状态：0-禁用，1-启用
    - **page_num**: 页码，从1开始，默认1
    - **page_size**: 每页记录数，默认10
    """
    try:
        filters = {
            "name": name,
            "code": code,
            "status": status
        }
        # 移除None值
        filters = {k: v for k, v in filters.items() if v is not None}
        
        result = merchant_service.get_merchant_list(db, filters, page_num, page_size)
        
        return create_response(
            message="查询成功",
            data=result
        )
    except Exception as e:
        return create_response(code=500, message=f"查询失败: {str(e)}")

@router.get("/{merchant_id}", response_model=schemas.Response)
async def get_merchant(
    merchant_id: int,
    db: Session = Depends(get_db)
):
    """
    获取商户详情
    
    - **merchant_id**: 商户ID
    """
    try:
        merchant = merchant_service.get_merchant_by_id(db, merchant_id)
        if not merchant:
            return create_response(code=404, message="商户不存在")
        
        return create_response(
            message="查询成功",
            data={
                "merchantId": merchant.id,
                "name": merchant.name,
                "code": merchant.code,
                "contactPerson": merchant.contact_person,
                "contactPhone": merchant.contact_phone,
                "address": merchant.address,
                "status": merchant.status,
                "remark": merchant.remark,
                "createTime": merchant.created_at.strftime("%Y-%m-%d %H:%M:%S")
            }
        )
    except Exception as e:
        return create_response(code=500, message=f"查询失败: {str(e)}")

@router.post("/create", response_model=schemas.Response)
async def create_merchant(
    merchant: schemas.MerchantCreate,
    db: Session = Depends(get_db)
):
    """
    创建商户
    
    - **name**: 商户名称
    - **code**: 商户编码
    - **contact_person**: 联系人
    - **contact_phone**: 联系电话
    - **address**: 地址
    - **status**: 状态
    - **remark**: 备注
    """
    try:
        # 检查编码是否已存在
        existing = db.query(schemas.Merchant).filter(schemas.Merchant.code == merchant.code).first()
        if existing:
            return create_response(code=400, message=f"商户编码'{merchant.code}'已存在")
        
        result = merchant_service.create_merchant(db, merchant.dict())
        
        return create_response(
            message="创建成功",
            data={
                "merchantId": result.id,
                "name": result.name,
                "code": result.code
            }
        )
    except Exception as e:
        return create_response(code=500, message=f"创建失败: {str(e)}")

@router.put("/{merchant_id}", response_model=schemas.Response)
async def update_merchant(
    merchant_id: int,
    merchant: schemas.MerchantUpdate,
    db: Session = Depends(get_db)
):
    """
    更新商户
    
    - **merchant_id**: 商户ID
    - **name**: 商户名称
    - **code**: 商户编码
    - **contact_person**: 联系人
    - **contact_phone**: 联系电话
    - **address**: 地址
    - **status**: 状态
    - **remark**: 备注
    """
    try:
        result = merchant_service.update_merchant(db, merchant_id, merchant.dict(exclude_unset=True))
        if not result:
            return create_response(code=404, message="商户不存在")
        
        return create_response(
            message="更新成功",
            data={
                "merchantId": result.id,
                "name": result.name,
                "code": result.code
            }
        )
    except Exception as e:
        return create_response(code=500, message=f"更新失败: {str(e)}")

@router.delete("/{merchant_id}", response_model=schemas.Response)
async def delete_merchant(
    merchant_id: int,
    db: Session = Depends(get_db)
):
    """
    删除商户
    
    - **merchant_id**: 商户ID
    """
    try:
        success = merchant_service.delete_merchant(db, merchant_id)
        if success:
            return create_response(message="删除成功")
        else:
            return create_response(code=404, message="商户不存在或删除失败")
    except Exception as e:
        return create_response(code=500, message=f"删除失败: {str(e)}") 